const WechatAPI = require('wechat-api');
import cacheClient from '../lib/core/cacheClient';
const config = require('../../config')
export const api = new WechatAPI(
  config.wechat.pub.appId,
  config.wechat.pub.appSecret,
  async callback => {
    try {
      const token = await cacheClient.get('wxApiToken', 'share');
      callback(null, token);
    } catch (err) {
      callback(err);
    }
  },
  async (token, callback) => {
    try {
      await cacheClient.setex('wxApiToken', 'share', 360, token);
      callback(null, token);
    } catch (err) {
      callback(err);
    }
  }
);
export default class WechatService {
  public static async sendWechatTemplateMessage(wechatPubOpenId, type, url, params) {
    const templateIds = [
      '6mQ9rOiKhhiy_XYSof7pwuiw8OpMNqjH7ktynZXig3I',
      'U6O-jBXpaxIJqdxvDmBaP5c6WlyhPogbYtjuWVSWBpg',
      'dgWHlun_ttgP1zALG9cDUGdHowu8EO2aavtUkYOdq40',
      '0RmmMUN3Qqe8E6gDGiJRDtHQ4QX31pUSoKuvFIC_x60'
    ];
    const templateId = templateIds[type];
    try {
      api.sendTemplate(wechatPubOpenId, templateId, url, params, (err, result) => {
        if (err) {
          console.log(err);
        }
      });
    } catch (err) {
      console.log(err);
    }
    return true;
  }
}
